package com.hhhn.wk.widget.versionsup.updataservice;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * * * * * * * * * * * *
 * @author：WenKe ｡◕‿◕｡ *
 * Data：2017     ｡◕‿◕｡ *
 * QQ：370820580  ｡◕‿◕｡ *
 * Function：     ｡◕‿◕｡ *
 * UpdataService
 * * * * * * * * * * * */
public class UpdataService extends Service {
    /** 安卓系统下载类 **/
    private DownloadManager manager;
    /** 接收下载完的广播 **/
    private DownloadCompleteReceiver receiver;
//  private String url;
    static public String DOWNLOADPATH = "/download/";//下载路径，如果不定义自己的路径，6.0的手机不自动安装
    static public String APPNAME = "";//app名字
    public UpdataService() {
    }
    public UpdataService(String APPNAME) {
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());

        this.APPNAME = simpleDateFormat.format(date)+APPNAME;
    }
    /** 初始化下载器 **/
    private void initDownManager(String updataUrl) {
        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        receiver = new DownloadCompleteReceiver();
        //设置下载地址  
        Request down = new Request(Uri.parse(updataUrl));
        // 设置允许使用的网络类型，这里是移动网络和wifi都可以  
        down.setAllowedNetworkTypes(Request.NETWORK_MOBILE
                | Request.NETWORK_WIFI);
        down.setAllowedOverRoaming(false);
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(updataUrl));
        down.setMimeType(mimeString);
        // 下载时，通知栏显示途中  
        down.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
        // 显示下载界面  
        down.setVisibleInDownloadsUi(true);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        // 设置下载后文件存放的位置
        down.setDestinationInExternalPublicDir(DOWNLOADPATH, APPNAME);
        // 将下载请求放入队列
        manager.enqueue(down);
        //注册下载广播  
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 调用下载
        initDownManager(intent.getStringExtra("updataUrl"));
        return super.onStartCommand(intent, flags, startId);  
    }
    @Override  
    public IBinder onBind(Intent intent) {  
      
        return null;  
    }
    @Override  
    public void onDestroy() {  
  
        // 注销下载广播  
        if (receiver != null)  
            unregisterReceiver(receiver);  
          
        super.onDestroy();  
    }  
  
    // 接受下载完成后的intent  
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override  
        public void onReceive(Context context, Intent intent) {
            //判断是否下载完成的广播
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                //获取下载的文件id
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (manager.getUriForDownloadedFile(downId) != null) {
                    //自动安装apk
                    installAPK(manager.getUriForDownloadedFile(downId), context);
                } else {
                    Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                }
                //停止服务并关闭广播
                UpdataService.this.stopSelf();
            }
        }
        private void installAPK(Uri apk, Context context) {
            if (Build.VERSION.SDK_INT < 23) {
                Intent intents = new Intent();
                intents.setAction("android.intent.action.VIEW");
                intents.addCategory("android.intent.category.DEFAULT");
                intents.setType("application/vnd.android.package-archive");
                intents.setData(apk);
                intents.setDataAndType(apk, "application/vnd.android.package-archive");
                intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intents);
            } else {
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +DOWNLOADPATH+ APPNAME);
                if (file.exists()) {
                    openFile(file, context);
                }
            }
        }
    public void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }
    }
    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }


    }
}  
